use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::common::{EnvVision, Response};

#[derive(Clone, Debug, Serialize)]
pub struct QuerySchemeReq {
    scheme: String,
}

impl QuerySchemeReq {
    pub fn new<T>(scheme: T) -> Self
    where
        T: AsRef<str>,
    {
        Self {
            scheme: scheme.as_ref().to_owned(),
        }
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct QuerySchemeRes {
    pub scheme_info: SchemeInfo,
    pub visit_openid: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct SchemeInfo {
    pub appid: String,
    pub path: String,
    pub query: String,
    pub create_time: u32,
    pub expire_time: u32,
    pub env_vision: EnvVision,
}

pub async fn query_scheme<T>(
    token: T,
    req: &QuerySchemeReq,
) -> Result<Response<QuerySchemeRes>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = format!(
        "https://api.weixin.qq.com/wxa/queryscheme?access_token={}",
        token.as_ref().to_owned()
    );
    let client = Client::new();
    client
        .post(url)
        .json(req)
        .send()
        .await?
        .json::<Response<QuerySchemeRes>>()
        .await
}
